package com.wordsay.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import com.wordsay.common.Constant;
import com.wordsay.entity.HotItem;

public class FormulaUtil {

	/**
	 * compute the similar using linear weight method
	 * @param similarWordRate
	 * @param vectorA
	 * @param vectorB
	 * @return
	 */
	public static double computelinearWeigthSimilar(double similarWordRate,List<HotItem> vectorA,List<HotItem> vectorB){
		
		BigDecimal similarRate = new BigDecimal(0);
		
		double sum = 0;
		for(int i = 0; i < vectorA.size();i++){
			
			sum += vectorA.get(i).getHotRate().doubleValue() + vectorB.get(i).getHotRate().doubleValue();
		}
		
		similarRate = (new BigDecimal(similarWordRate)).multiply(new BigDecimal(sum));
		
		return similarRate.setScale(2, RoundingMode.HALF_UP).doubleValue();
		
	}
	
	/**
	 * compute similar word rate
	 * @param similarWordsCount
	 * @param totalWordCount
	 * @return
	 */
	public static double computeSimilarWordRate(int similarWordsCount,int personAWordCount,int personBWordCount){
		
		if(personAWordCount == 0 || personBWordCount == 0){
		    return 0;
		}
		
		int totalWordCount = personAWordCount <= personBWordCount ? personAWordCount : personBWordCount;
		
		BigDecimal rate = (new BigDecimal(similarWordsCount)).divide(new BigDecimal(totalWordCount));
		return rate.setScale(Constant.DIVIDE_SCALE, RoundingMode.HALF_UP).doubleValue();
	}
	
	/**
	 * 计算向量cos值
	 * @param vectorA
	 * @param vectorB
	 * @return
	 */
	public static double cosTwoVectorsAngle(List<HotItem> vectorA,List<HotItem> vectorB){
		
		BigDecimal numerator = new BigDecimal(0);
		double factorA = 0;
		double factorB = 0;
		
		for(int i = 0; i < vectorA.size(); i++){
			
			HotItem a = vectorA.get(i);
			HotItem b = vectorB.get(i);
			
			numerator= numerator.add(a.getHotRate().multiply(b.getHotRate()));	
			
			factorA += Math.pow(a.getHotRate().doubleValue(), 2);
			factorB += Math.pow(b.getHotRate().doubleValue(), 2);
		}
		
		factorA = Math.sqrt(factorA);
		factorB = Math.sqrt(factorB);
		
		
		BigDecimal denominator = (new BigDecimal(factorA)).multiply(new BigDecimal(factorB));
	
		BigDecimal cosValue = numerator.divide(denominator,7,RoundingMode.HALF_UP);
		
		//精确到小数点后2位,且四舍五入
        cosValue = cosValue.setScale(4, RoundingMode.HALF_UP);
		
		return cosValue.doubleValue();
		
	}
	
	
}
